package com.fengye.lock.redis.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.fengye.lock.redis.domain.UserReg;
import com.fengye.lock.redis.dto.UserDTO;
import com.fengye.lock.redis.mapper.UserRegMapper;
import com.fengye.lock.redis.service.UserRegService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

/**
 *
 */
@Service
@Slf4j
public class UserRegServiceImpl extends ServiceImpl<UserRegMapper, UserReg>
        implements UserRegService {

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    /**
     * 根据用户名查询用户
     * @param username 用户名
     * @return com.fengye.lock.redis.domain.UserReg
     */
    @Override
    public UserReg selectByUsername(String username) {
        QueryWrapper<UserReg> wrapper = new QueryWrapper<>();
        wrapper.eq("user_name", username);
        UserReg userReg = this.baseMapper.selectOne(wrapper);
        return userReg;
    }

    @Override
    public void userRegNoLock(UserDTO dto) throws Exception {
        UserReg userReg = this.selectByUsername(dto.getUsername());
        if (userReg == null) {
            UserReg reg = new UserReg();
            reg.setUserName(dto.getUsername());
            reg.setPassword(dto.getPassword());
            reg.setCreateTime(new Date());
            log.info("reg={}", reg);
            this.save(reg);

        } else {
            throw new Exception("用户已存在");
        }
    }

    @Override
    public void userRegWithLock(UserDTO dto) throws Exception {

        // 精心设计并构造 SETNX 操作中的 Key，一定要跟实际的业务或共享资源挂钩
        final String key = dto.getUsername() + "-lock";

        // value 具有随机性
        final String value = System.nanoTime() + "" + UUID.randomUUID();

        ValueOperations<String, String> valueOperations = stringRedisTemplate.opsForValue();

        // 调用 SETNX 操作获取锁，如果返回 true，则获取成功
        // true: 表示当前的共享资源还没被其他线程所占用
        Boolean result = valueOperations.setIfAbsent(key, value);

        if (result) {
            log.info("获取锁 key={}, value={},成功", key, value);


            // 为了防止死锁，加上 EXPIRE 操作，设置过期时间
            // TODO: 具体的值根据业务而定
            stringRedisTemplate.expire(key, 20L, TimeUnit.SECONDS);

            try {
                UserReg userReg = this.selectByUsername(dto.getUsername());
                if (userReg == null) {
                    log.info("使用 redis 实现分布式锁，当前需要注册的用户为：{}", dto);
                    UserReg reg = new UserReg();
                    reg.setUserName(dto.getUsername());
                    reg.setPassword(dto.getPassword());
                    reg.setCreateTime(new Date());
                    log.info("reg={}", reg);
                    this.save(reg);
                }else{
                    throw new Exception("用户已存在");
                }
            } finally {
                // 删除当前线程创建的 key，即释放锁
                if (value.equals(valueOperations.get(key))) {
                    stringRedisTemplate.delete(key);
                    log.info("释放锁 key={}, value={}", key, value);
                }
            }
        }
    }
}




